package sc.udp.impl;


import java.io.IOException;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.Socket;

import org.apache.log4j.Logger;

import sc.helper.Helper;
import sc.tcp.TCPGateway;
import sc.udp.UDPGateway;

public class UDPReceiver implements Runnable {

	private Logger logger = Logger.getLogger(this.getClass());
	
	private final int PACKET_SIZE = 64*1024;
	
	private boolean isRunning = true;
	
	private UDPGateway udpGW;

	private TCPGateway tcpGW;
	
	private int port;

	public UDPReceiver(UDPGateway udpGW, TCPGateway tcpGW, int port) {
		this.udpGW = udpGW;
		this.tcpGW = tcpGW;
		this.port = port;
		logger.debug("Created");
	}
	
	public void run() {
		logger.debug("Started");
		while(isRunning) {
			try {
//				logger.debug("Waiting for UDP packet...");
				
				byte[] data = new byte[PACKET_SIZE];
				DatagramPacket packet = new DatagramPacket(data, PACKET_SIZE);

				udpGW.getSocket(port).receive(packet);
				
				int length = packet.getLength();
				int port = packet.getPort();
				byte[] newData = new byte[packet.getLength() + 4];
				newData[0] = (byte) ((length >> 8) & 0x000000ff);
				newData[1] = (byte) (length & 0x000000ff);
				newData[2] = (byte) ((port >> 8) & 0x000000ff);
				newData[3] = (byte) (port & 0x000000ff);	
				for (int i=0; i<packet.getLength(); i++) {
					newData[i+4] = packet.getData()[i];
				}

				tcpGW.write(newData);

//				logger.debug("UDP (" + packet.getAddress() + ":" + packet.getPort()
//							+ ") -> TCP (" + socket.getInetAddress().getHostAddress() + ":" + socket.getPort() + "):\n" + Helper.byteArrayToHexString(newData) );
				logger.debug("UDP (" + packet.getPort() + ") -> TCP:\n" + Helper.byteArrayToHexString(newData) );
								
			} catch (IOException e) {
				logger.debug("Disconnected");
				isRunning = false;
			}
			
		}
		logger.debug("Closed");
	}
	
}
